# -*- coding: utf-8 -*-
'''
Created on 2012-9-1

@author: xiaolei
'''
from flask.wrappers import Response
from flask.globals import request
from flask import json, Blueprint
from services import UserService
from models import User
from datetime import datetime, date, time
from common import secure_api

api = Blueprint("api", __name__);

def _generate_response(result=None, status="OK", message="", result_key_name="result"):
    if result != None:
        data = {"status": status};
        if result:
            data[result_key_name] = result;
        if message:
            data["message"] = message;
    else:
        data = None;
        
    resp = Response(json.dumps(data, indent=2), status=200, mimetype="application/json");
    return resp;

def _as_dict(obj):
    if  obj != None:
        result = {k:getattr(obj, k) if not getattr(obj, k).__class__ in (datetime, date, time) else str(getattr(obj, k)) for k in dir(obj) if k in obj.__table__.columns};
        return result;
    return obj;
        
@api.route("/user/email=<email>", methods=["GET"])
@secure_api
def get_user_by_email(email):
    user_service = UserService();
    result = _as_dict(user_service.get_user_by_email(email));
    return _generate_response(result);

@api.route("/user/add", methods=["POST"])
@secure_api
def add_user():
    data = request.json;
    if not data:
        raise Exception("content-type should contains a json format user instance.");
    user = User();
    user.display_name = data.get("DisplayName", None);
    user.email = data.get("Email", None);
    user.password = data.get("Password", None);
    user.PhoneNumber = data.get("PhoneNumber", None);
    
    user_service = UserService();
    new_id  = user_service.add_user(user);
    return _generate_response(new_id, result_key_name="new_id");


